import {BaseEvent, MetadataResponse, MouseEvent, MouseClick, MouseMove} from "../event-types";

export class MousePreparation {
    public prepareMouseEvents(data: BaseEvent[], metadata: MetadataResponse): MouseEvent[] {
        const result: MouseEvent[] = [];
        const mouseEvents = <(MouseMove | MouseClick)[]>data.filter(d => d.EventType === 'MouseMoveEvent' || d.EventType === 'ObjectActionEvent')
            .sort((a, b) => +a.Timestamp - +b.Timestamp);
        let latestMoveEvent: MouseMove | undefined = undefined;
        let latestClickEvent: MouseClick | undefined = undefined;
        for (let mouseEvent of mouseEvents) {
            if (mouseEvent.EventType === 'MouseMoveEvent') {
                latestMoveEvent = mouseEvent;
            }
            if (mouseEvent.EventType === 'ObjectActionEvent') {
                latestClickEvent = mouseEvent;
            }

            if (!latestMoveEvent) {
                continue;
            }
            const event: MouseEvent = {
                eventType: 'mouse-event',
                left: latestClickEvent?.Event.LeftButton ?? false,
                right: latestClickEvent?.Event.RightButton ?? false,
                middle: latestClickEvent?.Event.MiddleButton ?? false,
                x: latestMoveEvent.Event.X,
                y: latestMoveEvent.Event.Y,
                timestamp: Math.max(+latestMoveEvent.Timestamp, +(latestClickEvent?.Timestamp ?? -1)),
                up: latestClickEvent?.Event?.Up ?? false
            };
            result.push(event);
        }
        return result;
    }
}